import React, { Component, cloneElement } from 'react';
import PropTypes from 'prop-types';

import styles from './style.scss';

export default class Collapse extends Component {
    static propTypes = {
        defaultActiveKeys: PropTypes.array,
        activeKeys: PropTypes.array,
        accordion: PropTypes.bool,
        onChange: PropTypes.func,
        children: PropTypes.any,
        className: PropTypes.string,
        style: PropTypes.object,
    };

    static defaultProps = {
        defaultActiveKeys: [],
        accordion: false,
        onChange: () => null,
    };

    constructor(props) {
        super(props);

        this.state = {
            activeKeys: 'activeKeys' in props ? props.activeKeys : props.defaultActiveKeys,
        };
    }

    componentWillReceiveProps(nextProps) {
        if ('activeKeys' in nextProps) {
            this.setState({
                activeKeys: nextProps.activeKeys
            });
        }
    }

    onItemClick(key) {
        let activeKeys = this.state.activeKeys;
        if (this.props.accordion) {
            activeKeys = activeKeys[0] === key ? [] : [key];
        } else {
            activeKeys = [...activeKeys];
            const idx = activeKeys.indexOf(key);
            if (idx === -1) {
                activeKeys.push(key);
            } else {
                activeKeys.splice(idx, 1);
            }
        }
        if (!('activeKeys' in this.props)) {
            this.setState({
                activeKeys
            });
        }
        this.props.onChange(activeKeys);
    }

    renderItems() {
        const { activeKeys } = this.state;
        const { children, accordion } = this.props;
        return React.Children.map(children, (child, idx) => {
            const key = child.key || String(idx);
            const active = activeKeys.indexOf(key) !== -1;
            const props = {
                key,
                active,
                accordion,
                children: child.props.children,
                onClick: child.props.disabled ? null : () => this.onItemClick(key),
            };
            return cloneElement(child, props);
        });
    }

    render() {
        const { className, style } = this.props;
        let cls = styles.collapse;
        if (className) {
            cls += ' ' + className;
        }
        return (
            <ul className={cls} style={style}>
                { this.renderItems() }
            </ul>
        );
    }
}